package com.project.modules.netty;

import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 通道初始化对象
 */
@Component
@Slf4j
public class WebSocketChannelInit extends ChannelInitializer {
    @Autowired
    private WebSocketHandler webSocketHandler;

    @Override
    protected void initChannel(Channel channel) throws Exception {
        log.info("收到新连接");
        ChannelPipeline pipeline = channel.pipeline();
        // websocket本身是基于http协议的，对http协议的支持.
        pipeline.addLast("httpCodec", new HttpServerCodec());
        // 对大数据流的支持
        pipeline.addLast("chunkedWriteHandler", new ChunkedWriteHandler());
        //post请求分三部分. request line / request header / message body
        // HttpObjectAggregator将多个信息转化成单一的request或者response对象
        pipeline.addLast("httpAggregator", new HttpObjectAggregator(8192));
        // 将http协议升级为ws协议. websocket的支持
        pipeline.addLast("websocketProtocolHandler",
                new WebSocketServerProtocolHandler("/ws", null, true, 65536 * 10));
        // 自定义处理handler
        pipeline.addLast(webSocketHandler);
    }
}

